//
//  Status.swift
//  XDweibo
//
//  Created by HanXingda on 15/7/1.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import AFNetworking
import SDWebImage

//访问微博首页地址
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"
//https://api.weibo.com/2/statuses/public_timeline.json
class Status: NSObject {
    
    /**
    *  微博模型属性
    */
    //创建微博时间
    var created_at : String?
    
    //微博ID
    var id: Int = 0
    
    //微博信息内容
    var text : String?
    
    //微博来源
    var source: String?
    
    //User模型
    var user: User?
    
    //被转发微博模型
    var retweeted_status: Status?
    
    //配图数组
    var pic_urls:[[String : String]]? {
        didSet {
            //定义imageURL数组
            imageURLs = [NSURL]()
            //定义largeURL数组
            largeImageURLs = [NSURL]()
            //遍历，生成每张图片的url
            for dict in pic_urls! {
                 var urlString = dict["thumbnail_pic"]!
                //缩略图的URL
                imageURLs?.append(NSURL(string: urlString)!)
            
                //大图的URL
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                largeImageURLs?.append(NSURL(string: urlString)!)
            }
        }
    }
    
    //配图的URL 数组
    var imageURLs : [NSURL]?
    //定义大图URL 数组
    var largeImageURLs : [NSURL]?
    var largePicURLs : [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.largeImageURLs : largeImageURLs
    }
    
    //配图的属性判断
    var PicURLs  : [NSURL]? {
        return  retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    }
    
    //类属性数组
    static let properties = ["created_at","id","text","source","user","pic_urls","retweeted_status"]
    
    //字典转模型函数
    init(dict:[String : AnyObject]) {
        super.init()
        for key in Status.properties {
            // 判断自字典中对应的属性是否存在
            if dict[key] == nil || key == "user" || key == "retweeted_status" {
                continue
            }
            //如果有用KVC设置数值
            setValue(dict[key], forKey: key)
        }
        //判断字典中是否有user
        if let userDict = dict["user"] {
            user = User(dict: userDict as! [String : AnyObject])
        }
        //判断字典中是否有retweeted_status
        if let retweetedDict = dict["retweeted_status"] {
            retweeted_status = Status(dict: retweetedDict as! [String : AnyObject])
        }
    }
    //打印状态信息
    override var description: String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
    
    ///  加载数据
    /**
    since_id    若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    max_id      若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    */
    class func loadStatus(since_id: Int, max_id: Int, finished:(array : [Status]?, error : NSError?) -> ()) {
        assert(sharedUserAccount != nil, "必须登录之后才能访问网络")
        var parames = ["access_token" : sharedUserAccount!.access_token]

        if since_id > 0 {
            parames["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parames["since_id"] = "0"
            parames["max_id"] = "\(max_id - 1)"
        }
        
        
        //发起网络请求，异步加载数据
        NetWorkTools.sharedNetworkTools().GET(WB_Home_Timeline_URL, parameters: parames, success: { (_, JSON) -> Void in
            
            //从返回字典中获取status数组
            if let array = JSON["statuses"] as? [[String : AnyObject]]{
                print(array)
            // 1. 获得微博的模型数组
            let list = statuses(array)
            
            // 2. 异步缓存微博模型数组中得所有图片
            cacheImages(list, finished: finished)
                
                return
            }
            
            finished(array: nil, error: nil)
            
            }) { (_, error) -> Void in
                print(error)
                finished(array: nil, error: error)
        }
    }
    
    //字典转模型
    class func statuses(array: [[String : AnyObject]]) -> [Status] {
        
        //定义可变数组
        var arrayM = [Status]()
        
        //遍历传进来的数据数组
        for dict in array {
            //把属性模型保存到可变数组
            arrayM.append(Status(dict: dict))
        }
        return arrayM
        
    }
    
    //缓存微博数组中所有图像
    //缓存万所有图像后，再通知调用方更新所有图片
    /**
    *  要解决的问题：所有图片`被缓存完成`后，统一回调
    知识点：dispatch_group_enter
    */
    private class func cacheImages(list: [Status],finished:(array : [Status]?, error : NSError?) -> ()) {
        
        // 1. 定义调度组
        let group = dispatch_group_create()
        // 2. 遍历数组
        for s in list {
            // 判断imageURL中是否有有内容
            if s.PicURLs == nil || s.PicURLs!.isEmpty {
                continue
            }
            // 2. 进一步遍历 imageURLs 的数组，缓存数组中的图片
            for url in s.PicURLs! {
                //进入组
                dispatch_group_enter(group)
                
                // 用 sdwebimage 缓存图片 downloadImageWithURL 是 SDWebImage 核心的图像下载函数
              
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    //离开组
                    dispatch_group_leave(group)
                })
            }
        }
        
        //监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //完成回调
            finished(array: list, error: nil)
        }
        
        
        
    }

}
